/*
 * Login.cpp
 *
 *  Created on: 2013-2-5
 *      Author: Administrator
 */

#include "Login.h"

Login::Login(QWidget *parent):QDialog(parent), nameLabel("登录名"),
passwdLabel("密码"), messgLabel("欢迎使用本系统，请登录"), loginButton("登录"), exitButton("服务器设置"),db(Dao.db)
{
	ui();
}

void Login::ui()
{
	this->setAttribute(Qt::WA_DeleteOnClose,true);
	layout.addWidget(&messgLabel, 0, 0, 1, 2);
	layout.addWidget(&nameLabel, 1, 0);
	layout.addWidget(&nameEdit, 1, 1);
	layout.addWidget(&passwdLabel, 2, 0);
	layout.addWidget(&passwdEdit, 2, 1);
	passwdEdit.setEchoMode(QLineEdit::Password);
	layout.addWidget(&loginButton, 3, 0);
	layout.addWidget(&exitButton, 3, 1);
	this->setLayout(&layout);

	nameEdit.setText(Dao.value("signName","").toString());

	connect(&loginButton, SIGNAL(clicked()), this, SLOT(slt_check()));
	connect(&nameEdit, SIGNAL(textEdited(const QString &)), this, SLOT(slt_setMessg(const QString &)));
	connect(&passwdEdit, SIGNAL(textEdited(const QString &)), this, SLOT(slt_setMessg(const QString &)));
	connect(&exitButton, SIGNAL(clicked()), this, SLOT(slt_serverCheck()));

	/*db.setHostName(
			Dao.value("ServerIp","127.0.0.1").toString()
		//	"192.168.1.1"
		);
	db.setUserName("hoyt");
	db.setDatabaseName("Gemdale");
	db.setPassword("tian");
	db.setPort(
			Dao.value("ServerPort",3306).toInt()
	);*/
}

void Login::slt_serverCheck(){
		Dao.setServer();
}

void Login::slt_check()
{
	QSqlQuery query(Dao.getDateBase());
	query.exec(QString("SELECT * FROM user WHERE signName = '%1'").arg(nameEdit.text()));
	QSqlRecord r = query.record();
	if(!query.next())
	{
		messgLabel.setText("<h2><font color = red>登录名不存在！</font></h2>");
		return;
	}
	if((query.value(r.indexOf("password")).toString() != passwdEdit.text()) || (passwdEdit.text() == 0))
	{
		messgLabel.setText("<h2><font color = red>密码错误！</font></h2>");
		return;
	}
	if(query.value(r.indexOf("locked")).toBool() == true)
	{
		messgLabel.setText("<h2><font color = red>该用户已被锁定！</font></h2>");
		return;
	}
	Dao.user.setId(query.value(r.indexOf("id")).toUInt());
	Dao.user.setName(query.value(r.indexOf("name")).toString());
	Dao.user.setType((User::Type)query.value(r.indexOf("type")).toInt());
	Dao.user.setPassword(query.value(r.indexOf("password")).toString());
	Dao.user.setSignName(query.value(r.indexOf("signName")).toString());
	Dao.setValue("signName",Dao.user.getSignName());
	if(Dao.user.getType() == User::SaleManager)
	{
		UserCenter* uc = new UserCenter(Dao.user);
		uc->show();
	}
	else
	{
		DirectorMain* main = new DirectorMain;
		main->show();
	}

	this->close();
}

Login::~Login() {
	// TODO Auto-generated destructor stub
	qDebug()<<"Login Window Destoryed!";
}

